import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  ProfileEditAction,
  updatePeofileAction,
  updatePhotoAction,
} from '@/store/action/user';
import { DatePicker, Dialog, List, Toast } from 'antd-mobile';
import Input from '@/components/Input';
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import styles from './styles.module.scss';
import { Popup } from 'antd-mobile';
import { useState } from 'react';
import { ProFileType } from '@/store/reducers/user';
import Textarea from '@/components/Textarea';
import dayjs from 'dayjs';
import { clearToken } from '@/utils/storage';
import { useHistory } from 'react-router-dom';
// import { DemoBlock } from 'demos'
export default function ProfileEdit() {
  // 定义类型，复用弹出框
  type EditType = 'photo' | 'gender' | 'name' | 'intro'; //字面量
  const [editType, setEditType] = useState('' as EditType); //字面量+断言
  const [visible, setVisible] = useState(false);
  const [birthvisible, setBirthVisible] = useState(false); //控制日历
  const [rightVisible, setRightVisible] = useState(false);
  // state.user获取是reducer下的index
  const { profile } = useAppSelector((state) => state.user);
  // 把ref绑定给input,给泛型返回值类型绑定
  const ploadRef = useRef<HTMLInputElement>(null);
  const dispatch = useDispatch();
  const [nameVal, setNameVal] = useState('');
  const [intro, setIntro] = useState('');
  const now = new Date();
  const history = useHistory();
  useEffect(() => {
    dispatch(ProfileEditAction());
  }, [dispatch]);
  // 点击本地选择打开ref
  const handleUploadFn = () => {
    console.log(22);
    // 可选链
    ploadRef.current?.click();
  };
  // params有自动返回值类型
  const handleUpdateFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      console.log(e.target.files[0]);
      // 原生上传图片
      let formData = new FormData();
      formData.append('photo', e.target.files[0]); //第一个参数是后台参数，第二个就是传进来的
      await dispatch(updatePhotoAction(formData));
      // 关闭Popup弹出框
      setVisible(false);
      Toast.show({
        icon: 'success',
        content: '更新成功',
      });
    }
  };
  // 复用模态框
  const handleShowEdit = (type: EditType) => {
    setVisible(true);
    setEditType(type);
  };
  // 选择性别
  const handleUpdateProfile = async (data: Partial<ProFileType>) => {
    await dispatch(updatePeofileAction(data));
    setVisible(false);
    Toast.show({
      content: '更新成功',
    });
  };
  //名字 setRightVisible(true)
  const handlerightVisbile = (type: EditType) => {
    setRightVisible(true);
    setEditType(type);
  };
  // useEffect监听

  useEffect(() => {
    setNameVal(profile.name || '');
  }, [profile.name]);
  // 编辑默认值
  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);
  // 点击提交
  const handleSubmit = async (data: Partial<ProFileType>) => {
    await dispatch(updatePeofileAction(data));
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
    Toast.show({
      content: '更新成功',
    });
  };
  // bug,点击编辑后退，inp框内容还是之前的
  const handleBack = () => {
    setRightVisible(false);
    editType === 'name' && setNameVal(profile.name);
    editType === 'intro' && setNameVal(profile.intro);
  };
  // 回车事件
  const handleKeyDown = (
    e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    if (e.key === 'Enter') {
      editType === 'name' && handleSubmit({ name: nameVal });
      editType === 'intro' && handleSubmit({ intro });
      Toast.show({
        content: '更新成功',
      });
    }
  };
  // 退出登录
  const handleLogout = () => {
    // 退出登录一般用Dialog
    Dialog.confirm({
      title: '温馨提示',
      content: '是否退出',
      onConfirm: () => {
        // 二次确定
        // 清除token
        clearToken();
        // 跳转
        history.push('/login');
        Toast.show({
          icon: 'success',
          content: '退出成功',
          position: 'bottom',
        });
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人信息</NavBar>
        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              onClick={() => handleShowEdit('photo')}
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => handlerightVisbile('name')}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handlerightVisbile('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handleShowEdit('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          {/* 绑定ref,方便别人打你 */}
          <input
            className="avatar-upload"
            type="file"
            ref={ploadRef}
            onChange={(e) => handleUpdateFile(e)}
          />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>
      <Popup
        visible={visible}
        onMaskClick={() => setVisible(false)}
        bodyClassName="popup-bottom-list"
      >
        {editType === 'photo' && (
          <>
            <div className="list-item" onClick={handleUploadFn}>
              拍照
            </div>
            <div className="list-item" onClick={handleUploadFn}>
              本地选择
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
        {editType === 'gender' && (
          <>
            <div
              className="list-item"
              onClick={() => handleUpdateProfile({ gender: 0 })}
            >
              男
            </div>
            <div
              className="list-item"
              onClick={() => handleUpdateProfile({ gender: 1 })}
            >
              女
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
      </Popup>
      {/* 右侧弹出 */}
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {editType === 'name' && (
          <>
            <NavBar
              onBack={handleBack}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleSubmit({ name: nameVal })}
                >
                  提交
                </span>
              }
            >
              编辑用户信息
            </NavBar>
            <div className="edit-content">
              <h3 className="edit-title">编辑昵称</h3>
              {/* 改造成受控组件 */}
              <Input
                className="edit-input"
                value={nameVal}
                onChange={(e) => setNameVal(e.target.value)}
                // 只有第一次的时候可以有聚焦，第二次antd-mobile组件还存在，为了节流，组件还存在，所以要做一下组件销毁的行为
                //  回车事件
                onKeyDown={(e) => handleKeyDown(e)}
                autoFocus
              />
            </div>
          </>
        )}
        {editType === 'intro' && (
          <>
            <NavBar
              onBack={handleBack}
              right={
                <span
                  className="submit-btn"
                  onClick={() => handleSubmit({ intro })}
                >
                  提交
                </span>
              }
            >
              编辑简介
            </NavBar>
            <div>
              <div className={styles.root}>
                <Textarea
                  value={intro}
                  maxLength={100}
                  onChange={(e) => setIntro(e.target.value)}
                ></Textarea>
                {/* <div className="count">
                  {value.length}/{maxLength}
                </div> */}
              </div>
            </div>
          </>
        )}
        {/* 封闭默认行为,不然直接关闭页面 */}
      </Popup>

      <DatePicker
        visible={birthvisible}
        title="选择生日"
        onClose={() => {
          setBirthVisible(false);
        }}
        value={now}
        min={new Date('1920-1-1')}
        max={now}
        onConfirm={(val) =>
          handleSubmit({ birthday: dayjs(val).format('YYYY-MM-DD') })
        }
      />
    </div>
  );
}
